//用户模块
import router from '@/router';
const state = {
    set token(value:any){
        localStorage.setItem('token',value);
    },
    get token():any{
        return window.localStorage.getItem('token')
    },
    set userInfo(value:any){
        window.localStorage.setItem('userInfo',JSON.stringify(value));
    },
    get userInfo(){
        return JSON.parse(<string>window.localStorage.getItem('userInfo'))
    },
    avatar: '',
}


const mutations = {
    /*设置token*/
    SET_TOKEN(state:any,userInfo:any):void{
        let { token, name , expire } = userInfo;
        state.userInfo = {
            userName: name,
            expire: expire * 1000
        }
        state.token = token;
    },

    /*设置用户头像*/
    SET_AVATAR(state:any,avatar:any):void{
        state.avatar = avatar;
    },

    /*删除用户信息*/
    REMOVE_TOKEN(state:any):void{
        state.token = "";
        state.userInfo = "";

        router.push('/login')
    }

}

const actions = {
    /*用户登录*/
    login({ commit }:any,userInfo:any):any {
        return new Promise<void>((resolve,reject)=>{
            commit('SET_TOKEN',userInfo)
            resolve()
        })
    },

    /*获取用户信息*/
    getUserAvatar({ commit , state }:any){
        return new Promise((resolve,reject)=>{
            commit('SET_AVATAR','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif');
            resolve(state.userInfo)
        })
    },

    /*用户退出*/
    loginOut({ commit, dispatch }:any):void {
        commit('REMOVE_TOKEN');
        dispatch('permission/removeRoute',true,{ root: true });
    },

    /*权限路由设置*/
    async changeRoles({ dispatch }:any){
        const rote = await dispatch('getUserAvatar');
        if(!rote){
            console.error("登录失败！")
            dispatch('loginOut')
            return;
        }
        const accessRoutes = await dispatch('permission/getAuthRouter',rote,{ root: true });
        accessRoutes.forEach((item:any,index:any)=> {
            router.addRoute(item);
        })
        await router.push('/')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

